#!/usr/bin/perl
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use Data::Dumper;
use Getopt::Long;
use DBI;

my ($subject_name, $sample_name, $capture_lib, $barcode, $debug);
my @argv = @ARGV;
&GetOptions("debug!"=> \$debug,
						"subject_name=s" => \$subject_name,
						"sample_name=s" => \$sample_name,
						"capture_lib=s" => \$capture_lib,
            "barcode=s" => \$barcode);

if ((!$subject_name) || (!$capture_lib)) {
	die "usage: $0 --subject_name PSP7020 , --sample_name Project_00007PSP7020 --capture_lib Nimblegen_46Mb_v2 --barcode GCCAAT [--debug]\n(use --debug to preview what would be inserted into mysql table)\n";
}

my $table = `basename $0 .pl | sed s/insert//`;
chomp($table);
printf STDERR "Inserting $sample_name into table $table\n";
if ($debug) {
	printf "Debug mode. The following are the aguments\n";
}
else {
	my $newid=driver();
	printf STDERR "${subject_name} $sample_name $capture_lib $barcode %s\n", ($newid) ? "inserted into $table with SMID=$newid" : "already in $table\n\n";
}

sub driver {
	my $dbh = DBI->connect($ENV{dbi1}, $ENV{dbi2}, $ENV{dbi3}) or die "Couldn't connect to database: " . DBI->errstr;;
	my $subject_id = MyTools::fetchrow1col1_arrayref($dbh, "select SBID from Subject where ", {'SubjectName' => $subject_name}) or die "Subject $subject_name not found\n";
	my $record_present = MyTools::fetchrow1col1_arrayref($dbh, "select SMID from $table where ", {'SubjectID' => $subject_id, 'SampleName' => $sample_name, 'CaptureLib' => $capture_lib, 'Barcode' => $barcode});
	if (defined($record_present)) {
		printf STDERR "Existing SMID=%d ", $record_present;
		return 0;
	}
	my $sth = $dbh->prepare("INSERT INTO $table (SubjectID,SampleName,CaptureLib,Barcode) VALUES (?,?,?,?)") or die "Couldn't prepare statement: " . $dbh->errstr;
	$sth->execute($subject_id, $sample_name, $capture_lib, $barcode) or die "Couldn't execute statement: " . $sth->errstr;
	return MyTools::fetchrow1col1_arrayref($dbh, "select SMID from $table where ", {'SubjectID' => $subject_id}, 'SampleName' => $sample_name, 'CaptureLib' => $capture_lib, 'Barcode' => $barcode);
}
